package cn.netjava.wk;


import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

public class SearchMonitor extends Thread{
	File file;
   FileSearch[]thread;
	private boolean monitor; 
    
	BufferedWriter write;
    public SearchMonitor(String dir,FileSearch[]thread) throws FileNotFoundException{
    	
    	monitor=true;
    	this.thread=thread;
		file=new File(dir);
	 if(!file.exists()){
		 try {
			file.createNewFile();
		} catch (IOException e) {			
			e.printStackTrace();
		}
	 }
     try {
		write=new BufferedWriter(new FileWriter(file));
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	 start();
 }
public void run(){
	while(monitor){
		int count=0;
		try {
		sleep(1000);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	for(int i=0;i<thread.length;i++){
		if(!thread[i].isAlive()){
			if(null!= thread[i].searchResoult()){
				Iterator it=thread[i].searchResoult().iterator();
			    while(it.hasNext()){
			    	try {
						write.append(it.next().toString()+"\n");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			    }
			}
		  count++;
		  try {
			write.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
				
	}
	if(count==thread.length)monitor=false;
	}
   
}
}
